using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using System.Runtime.InteropServices;
using System.IO;

namespace WMVConvert
{
	public class SplitInput: Task
	{
		ITaskItem[] videoInput;

		[Required]
		public ITaskItem[] InputVideo
		{
			get
			{
				return videoInput;
			}
			set
			{
				videoInput = value;
			}
		}

		int segmentSize;

		[Required]
		public int SegmentSize
		{
			get { return segmentSize; }
			set { segmentSize = value; }
		}

		List<ITaskItem> splittedInputVideo;

		[Output]
		public ITaskItem[] SplittedInputVideo
		{
			get
			{
				return splittedInputVideo.ToArray(); 
			}
			set
			{
				splittedInputVideo.Clear();
				splittedInputVideo.AddRange(value);
			}
		}

		public SplitInput()
		{
			splittedInputVideo = new List<ITaskItem>();
		}

		public override bool Execute()
		{
			foreach (ITaskItem item in videoInput)
			{
				MediaTaskItem mediaTaskItem = new MediaTaskItem(item);
				if (mediaTaskItem.PlayTime > 0)
				{
					int segments = (int)(mediaTaskItem.PlayTime / (long)segmentSize);
					int rest = (int)(mediaTaskItem.PlayTime % (long)segmentSize);
					int i = 0;
					for (i = 0; i < segments; i++)
					{
						CreateSubItem(item, i, i * segmentSize, (i + 1) * segmentSize);
					}
					if (rest > 0)
					{
						CreateSubItem(item, i, i * segmentSize, (int)(mediaTaskItem.PlayTime));
					}
				}
			}
			return true;
		}

		private void CreateSubItem(ITaskItem item, int i,int start,int end)
		{
			FileInfo fi = new FileInfo(item.ItemSpec);
			string itemSpec = item.ItemSpec + "." + i.ToString() + ".wmv";
			TaskItem subItem = new TaskItem(itemSpec, item.CloneCustomMetadata());
			subItem.SetMetadata("Start", start.ToString());
			subItem.SetMetadata("End", end.ToString());
			subItem.SetMetadata("Source", fi.FullName);
			subItem.SetMetadata("Segment", i.ToString());
			splittedInputVideo.Add(subItem);
		}
	}
}
